package top.infopub.mgr.mkt.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.BidAnalysisDto;
import top.infopub.enums.mkt.*;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.exception.FlowProcessException;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.hr.dao.StaffInfoDao;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.BidCurrencyDomain;
import top.infopub.mgr.mkt.jsonvo.BidAnalysisJsonVo;
import top.infopub.mgr.mkt.service.BidAnalysisService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.BidCurrencyVo;
import top.infopub.mgr.om.dao.PaymentApplyDao;
import top.infopub.mgr.om.dao.PaymentApplyDetailDao;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.*;
import top.infopub.model.om.PaymentApply;
import top.infopub.model.om.PaymentApplyDetail;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class BidAnalysisServiceImpl extends GenericServiceImpl<BidAnalysis, String> implements BidAnalysisService {

    @Autowired
    private BidAnalysisDao bidAnalysisDao;

    @Autowired
    private BidReqDao bidReqDao;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private BidInfoDao bidInfoDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private PaymentApplyDao paymentApplyDao;

    @Autowired
    private StaffInfoDao staffInfoDao;

    @Autowired
    private PaymentApplyDetailDao paymentApplyDetailDao;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private OAFlowService oaFlowService;

    @Override
    public GenericDao<BidAnalysis, String> getDao() {
        return bidAnalysisDao;
    }

    @Override
    public Page<BidCurrencyDomain> selectPage(Page<BidCurrencyDomain> page, BidCurrencyVo bidCurrencyVo) {
        //处理时间范围
        if (!StringUtils.isEmpty(bidCurrencyVo.getDates())) {
            String[] splitTime = bidCurrencyVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                bidCurrencyVo.setEndDate(format.parse(splitTime[1]));
                bidCurrencyVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<BidCurrencyDomain>)bidAnalysisDao.selectByDomainWhere(bidCurrencyVo);
    }

    @Override
    public BidAnalysisJsonVo queryDetailById(String id) {
        BidAnalysisJsonVo bidAnsJson = new BidAnalysisJsonVo();
        //基础信息
        BidAnalysisDto bidAnsDto = bidAnalysisDao.queryDetailById(id);
        ProjectFormatEnum pfe = ProjectFormatEnum.getByCode(bidAnsDto.getProFormat());
        if (pfe != null) {
            bidAnsDto.setProFormat(pfe.getName());
        }
        bidAnsJson.setInfo(bidAnsDto);

        //业绩要求
        bidAnsJson.setYjList(bidReqDao.queryByWhere(bidAnsDto.getId(), BidReqTypeEnum.BID_REQ_YJ.getCode(), null));
        //奖项要求
        bidAnsJson.setJxList(bidReqDao.queryByWhere(bidAnsDto.getId(), BidReqTypeEnum.BID_REQ_JX.getCode(), null));
        //人员要求
        bidAnsJson.setRyList(bidReqDao.queryByWhere(bidAnsDto.getId(), BidReqTypeEnum.BID_REQ_RY.getCode(), null));

        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(bidAnsDto.getProCode(), ProjectFileTypeEnum.FILE_TYPE14.getCode(), null);
        bidAnsJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        return bidAnsJson;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo editDetail(BidAnalysis bidAnalysis, BidInfo bidInfo, List<BidReq> yjList, List<BidReq> jxList, List<BidReq> ryList, PaymentApply paymentApply, PaymentApplyDetail paymentApplyDetail, List<ProjectAttachment> attachmentList, AuthorizationVO vo, Integer submitType) {
        //根据pro_code查询项目基础信息
        ProjectInfo tmpProInfo = projectInfoDao.findByProCode(bidInfo.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        BidAnalysis tmpBidAns = bidAnalysisDao.selectByPrimaryKey(bidAnalysis.getId());
        if (tmpBidAns == null) return RspVo.getFailureResponse(400, "招标文件分析信息不存在");
        //判断审批状态
        if (StringUtils.isNotBlank(tmpBidAns.getProcessStatus())
                && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpBidAns.getProcessStatus())
                || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpBidAns.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }

        //更新招标文件分析
        bidAnalysis.setUptBy(vo.getId());
        bidAnalysis.setUptTime(new Date());
        bidAnalysisDao.modifyById(bidAnalysis);

        //更新投标信息
        BidInfo tmpBidInfo = bidInfoDao.queryByProCode(bidInfo.getProCode());
        if (tmpBidInfo == null) {
            bidInfo.setAddBy(vo.getId());
            bidInfo.setAddTime(new Date());
            bidInfo.setUptBy(vo.getId());
            bidInfo.setUptTime(new Date());
            bidInfoDao.insert(bidInfo);
        } else {
            bidInfo.setId(tmpBidInfo.getId());
            bidInfo.setUptBy(vo.getId());
            bidInfo.setUptTime(new Date());
            bidInfoDao.modifyById(bidInfo);
        }

        //招标文件要求更新
        bidReqDao.deleteByWhere(tmpBidAns.getId(), BidReqTypeEnum.BID_REQ_YJ.getCode(), null);
        if (yjList != null && yjList.size() > 0) {
            for (BidReq bidReq : yjList) {
                bidReq.setProCode(bidInfo.getProCode());
                bidReq.setBindAnalysisId(bidAnalysis.getId());
                bidReq.setReqType(BidReqTypeEnum.BID_REQ_YJ.getCode());
                bidReq.setAddBy(vo.getId());
                bidReq.setAddTime(new Date());
            }
            bidReqDao.insertBatch(yjList);
        }
        bidReqDao.deleteByWhere(tmpBidAns.getId(), BidReqTypeEnum.BID_REQ_JX.getCode(), null);
        if (jxList != null && jxList.size() > 0) {
            for (BidReq bidReq : jxList) {
                bidReq.setProCode(bidInfo.getProCode());
                bidReq.setBindAnalysisId(bidAnalysis.getId());
                bidReq.setReqType(BidReqTypeEnum.BID_REQ_JX.getCode());
                bidReq.setAddBy(vo.getId());
                bidReq.setAddTime(new Date());
            }
            bidReqDao.insertBatch(jxList);
        }
        bidReqDao.deleteByWhere(tmpBidAns.getId(), BidReqTypeEnum.BID_REQ_RY.getCode(), null);
        if (ryList != null && ryList.size() > 0) {
            for (BidReq bidReq : ryList) {
                bidReq.setProCode(bidInfo.getProCode());
                bidReq.setBindAnalysisId(bidAnalysis.getId());
                bidReq.setReqType(BidReqTypeEnum.BID_REQ_RY.getCode());
                bidReq.setAddBy(vo.getId());
                bidReq.setAddTime(new Date());
            }
            bidReqDao.insertBatch(ryList);
        }

        if (StringUtils.equals(YesOrNoEnum.YES.getCode(), bidInfo.getIsNeedBond())) {
            //付款申请
            String payApplyId = paymentApplyDao.querySguidByProCode(bidAnalysis.getProCode(), "2");
            if (StringUtils.isBlank(payApplyId)) {
                StaffInfo staffInfo = staffInfoDao.selectByPrimaryKey(vo.getHrStaffId());
                if (staffInfo == null) throw new FlowProcessException("获取不到对应的人员信息数据~");
                paymentApply.setCodes(IdFactory.getUUIDUpper());
                paymentApply.setProCode(bidAnalysis.getProCode());
                paymentApply.setProName(tmpProInfo.getProName());
                paymentApply.setProFormat(tmpProInfo.getProFormat());
                paymentApply.setHrOrgId(staffInfo.getPkOrg());
                paymentApply.setHrDeptId(staffInfo.getPkDept());
                paymentApply.setHrStaffApplyId(vo.getHrStaffId());
                paymentApply.setStaffName(staffInfo.getStaffName());
                paymentApply.setApplyPayDate(new Date());
                paymentApply.setPayTotal(bidInfo.getBondMoney());
                paymentApply.setPayReason("保证金付款申请");
                paymentApply.setAddBy(vo.getId());
                paymentApply.setAddTime(new Date());
                paymentApply.setTypes("2");
                paymentApplyDao.insert(paymentApply);
                payApplyId = paymentApply.getId();
            }

            //付款明细
            PaymentApplyDetail tmpPad = paymentApplyDetailDao.selectByPaymentApplyId(payApplyId);
            if (tmpPad == null) {
                paymentApplyDetail.setApplyId(payApplyId);
                paymentApplyDetail.setItemName("保证金付款");
                paymentApplyDetail.setPaySingle(paymentApply.getPayTotal());
                paymentApplyDetail.setAddBy(vo.getId());
                paymentApplyDetail.setAddTime(new Date());
                paymentApplyDetailDao.insert(paymentApplyDetail);
            } else {
                paymentApplyDetail.setId(tmpPad.getId());
                paymentApplyDetailDao.updateByIdSelective(paymentApplyDetail);
            }
        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(bidInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE14.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            //处理OA待办信息
            if (StringUtils.isNotBlank(tmpBidAns.getOaId())) {
                oaFlowService.finishOA(tmpBidAns.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(bidAnalysis.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE5, detailJson, bidAnalysis.getId(), bidInfo.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public BidAnalysis queryByProCode(String proCode) {
        return bidAnalysisDao.queryByProCode(proCode);
    }
}
